<template>
    <el-dialog :draggable="true" :destroy-on-close="true" :model-value="checkDialog" @close="onCancel"
        :close-on-click-modal="false" title="新增配件" width="70%" top="8vh" class="check-dialog">
        <h4 class="title_top">基本信息</h4>
        <el-form label-width="100" label-position="right">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="申请类型">
                        <el-select placeholder="申请类型" clearable v-model="tableDataList.type" class="item-input">
                            <el-option v-for="item in options6" :value="item.value" :label="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="服务商配件类型" v-if="tableDataList.type == 2">
                        <el-select placeholder="服务商配件类型" clearable v-model="tableDataList.networkSpareType"
                            class="item-input">
                            <el-option v-for="item in options3" :value="item.value" :label="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="收货地址类型">
                        <el-select placeholder="收货地址类型" clearable v-model="tableDataList.receiptAddrType"
                            @change="changeAddrType" class="item-input">
                            <el-option v-for="item in options4" :value="item.value" :label="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收货人姓名">
                        <el-input placeholder="收货人姓名" clearable class="item-input" v-model="tableDataList.receiptName" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收货人手机号">
                        <el-input v-model="tableDataList.receiptPhone" clearable placeholder="收货人手机号"
                            class="item-input item-input-phone" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="收货人地址">
                        <SingleAddress ref="addrsDom" :address="addrs" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="详细地址">
                        <el-input placeholder="收货人详细地址" clearable size="small" show-word-limit maxlength="200"
                            class="item-input_w" type="textarea"    :rows="2"
                            v-model="tableDataList.receiptAddress" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="table">
            <el-table :border="true" stripe resizable height="300px" :data="tableDataList.spareMaterialVos"
                :row-class-name="tableRowClassName" @cell-mouse-enter="onCellMouseEnter"
                @cell-mouse-leave="onCellMouseLeave">
                <el-table-column label="操作" width="75" fixed="left" align="center">
                    <template #default="scope">
                        <div v-show="styleColumn[scope.$index].tableColumnIndex">
                            <span>{{ scope.$index + 1 }}</span>
                        </div>
                        <div v-show="styleColumn[scope.$index].tableColumnBtn">
                            <span class="operation">
                                <el-icon @click="addItem" color="#007cff" size="16" class="icon">
                                    <CirclePlus />
                                </el-icon>
                                <el-icon color="rgba(245, 108, 108, 1)" size="16" class="icon"
                                    @click="deleteItem(scope.$index)">
                                    <RemoveFilled />
                                </el-icon>
                            </span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="结算类型" width="150">
                    <template #default="scope">
                        <el-select placeholder="结算类型" v-model="scope.row.type" filterable clearable>
                            <el-option v-for="item in options1" :value="item.value" :key="item.value" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="配件名称" width="140">
                    <template #default="scope">
                        <el-select placeholder="请选择" filterable clearable v-model="scope.row.spareId"
                            :remote-method="(val) => sparePageSelectList(val, scope.$index)" :loading="loading2"
                            @change="(id: any) => changeSpareId(id, scope.$index)" remote remote-show-suffix>
                            <el-option v-for="item in scope.row.spareSelect" :value="item.id" :label="item.name"
                                @click="clickSpareId(item, scope.$index)" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="型号" min-width="140" prop="model">
                    <template v-slot="i">
                        <el-input disabled v-model="i.row.model" readonly></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="规格" width="120">
                    <template #default="scope">
                        <el-select placeholder="请选择" filterable clearable v-model="scope.row.specId"
                            :remote-method="(val: any) => spareSpecPageSelectList(val, scope.row.spareId, scope.$index)"
                            :loading="loading2" remote remote-show-suffix
                            @change="(id: any) => clickSpecId(id, scope.$index)">
                            <el-option v-for="item in scope.row.spareSpecSelect" @click="clickspecId(item, scope.$index)"
                                :value="item.id" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="规格编码" min-width="160" prop="model">
                    <template v-slot="i">
                        <el-input disabled v-model="i.row.specSku" readonly></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料质保状态" width="150">
                    <template #default="scope">
                        <el-select placeholder="物料质保状态" v-model="scope.row.overinsured" filterable clearable
                            @change="onChangeOverinsured(scope.$index)">
                            <el-option v-for="item in options5" :value="item.value" :key="item.value" :label="item.name" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="申请数量" width="90">
                    <template #default="scope">
                        <el-input clearable @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
                            v-model="scope.row.qty" placeholder="数量" />
                    </template>
                </el-table-column>
                <el-table-column label="单价金额" width="120">
                    <template #default="scope">
                        <el-input clearable v-model="scope.row.price" @keyup="checkNum"
                            @input="scope.row.price = scope.row.price.replace(/[^\d.]/g, '')">
                            <template #prepend>￥</template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="总金额" width="120">
                    <template #default="scope">
                        <el-input disabled clearable :value="scope.row.price * scope.row.qty">
                            <template #prepend>￥</template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="备注" min-width="140" max-width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" clearable placeholder="填写备注" />
                    </template>
                </el-table-column>
                <el-table-column label="附件(最多上传8个)" width="460">
                    <template #default="scope">
                        <div class="updata_pic">
                            <el-upload action="#" multiple list-type="picture-card" accept="image/*,.pdf"
                                :auto-upload="false" :show-file-list="false"
                                :on-change="(file: any) => { getProImages(file, scope.$index) }">
                                <div class="plus_add">
                                    <el-icon size="12">
                                        <Plus />
                                    </el-icon>
                                </div>
                            </el-upload>
                            <div class="disf_ipc" v-for="(img, index) in scope.row.images">
                                <img :src="pdf" alt="" style="width: 100%;cursor: pointer"
                                    v-if="(img.image.replace(/.+\./, '') == 'pdf') || img.file?.type.includes('pdf')">
                                <img class="img" :src="img.image" v-else />
                                <span class="item-actions">
                                    <el-icon color="#fff" size="12" class="item-preview"
                                        @click="handlePictureCardPreview(img.image)"><zoom-in /></el-icon>
                                    <el-icon size="12" color="#fff" class="item-delete"
                                        @click="handleRemove(index, scope.$index)">
                                        <Delete />
                                    </el-icon>
                                </span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="footer_remark">
            <el-form-item label="申请备注" label-width="auto">
                <el-input type="textarea" class="w_input" size="small" show-word-limit maxlength="200"
                    :autosize="{ minRows: 2, maxRows: 4 }" v-model="tableDataList.remark" clearable placeholder="填写申请备注" />
            </el-form-item>
        </div>
        <div class="btns flex-justify-end">
            <el-button color="#007cff" class="btn_save" @click="onSaveBtn">提交申请</el-button>
            <el-button @click="onCancel" class="btn_cancel"> 取消 </el-button>
        </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible" draggable title="查看附件" top="8vh">
        <iframe :src="`${dialogImageUrl}`" style="height: 660px;width: 100%;" frameborder="0"></iframe>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, toRefs, nextTick, reactive, onMounted, watch } from 'vue'
// import { getOrderNetworkAddress, getWorkUserAddress, spareSaveOrder } from '../../../../../api/parts'
import { getOrderSparePageSelect, getOrderSpareSpecSelect } from '../../../../../api/order'
import { orderAnnexUpload } from '../../../../../api/upload'
import SingleAddress from '@/components/address/singleAddress.vue'
import pdf from '@/assets/image/pdf.png'
import { ElMessage, ElMessageBox } from 'element-plus'
import { checkNum } from '../../../../../utils/validate'
const props = defineProps({
    checkDialog: Boolean,
    workId: [String, Array]
})
const { checkDialog, workId } = toRefs(props)
const dialogVisible = ref(false)
const dialogImageUrl = ref(null)
const loading2 = ref(false)
const styleColumn = ref([{
    tableColumnBtn: false,
    tableColumnIndex: true,
}])
const emits = defineEmits(['assign-dialog', 'update-list'])
// 结算类型
const options1 = [{ name: '向服务商收取', value: 1 }, { name: '向服务商支付', value: 2 }, { name: '向客户收取', value: 3 }, { name: '向客户支付', value: 4 }]
// 服务商配件类型
const options3 = [{ name: '服务商-外部仓配件', value: 1 }, { name: '工程师-外部仓配件', value: 2 }, { name: '自购配件', value:3 }]
// 收货地址类型
const options4 = [{ name: '工单客户', value: 1 }, { name: '服务商', value: 2 }]
// 物料质保状态
const options5 = [{ name: '保内', value: false }, { name: '保外', value: true }]
// 申请类型
const options6 = [{ name: '平台配件', value: 1 }, { name: '外部配件', value: 2 }]
const tableDataList = reactive({
    "delSpareMaterialIds": [],//删除的工单配件物料对象
    "id": null,//
    "networkSpareType":1,//服务商配件类型：1-自购配件，2-服务商仓库配件
    "receiptAddrType": 1,//收货地址类型：1-工单客户地址，2-服务商地址,示例值(1)
    "receiptAddress": "",//收货人详细地址
    "receiptArea": "",//收货地址-县/区
    "receiptCity": "",//收货地址-市
    "receiptName": "",//收货人姓名
    "receiptPhone": "",//收货人手机号
    "receiptProvince": "",//收货地址-省
    "receiptTown": "",//收货地址-镇
    "remark": "",//备注
    "spareMaterialVos": [//工单配件物料对象
        {
            "delImageIds": [],//	删除的工单费用图片对象ID
            "id": null,//配件物料ID，新增不必传，修改必传	
            "images": [],
            "model": "",//物料型号
            "name": "",//物料名称
            "overinsured": false,//物料质保状态：false-保内，true-保外
            "price": 0,//物料单价
            "qty": 1,//	物料数量,示例值(1)
            "remark": "",//备注
            "spareId": null,//	物料配件ID
            "specId": null,//物料配件规格ID
            "specName": "",//	物料配件规格名称
            "specSku": "",//商品规格编号
            "type": 1,//结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
            spareSelect: [],//配件
            spareSpecSelect: [],//规格
        }
    ],
    "type": 1,//申请类型：1-商家配件，2-服务商配件,示例值(1)
    "userOrNetworkId": null,//用户/网点ID
    "workId": null//工单ID
})
const addrsDom = ref()
const addrs = ref({// 地址
    province: "",
    city: "",
    area: "",
    town: "",
})

// 给row对象赋索引值，注：在此赋值后，才可以在其他用到row的地址取值
const tableRowClassName = ({ row, rowIndex }) => {
    row.index = rowIndex
}
// 鼠标移入事件
const onCellMouseEnter = (row, column, cell, event, index) => {
    styleColumn.value[row.index].tableColumnBtn = true
    styleColumn.value[row.index].tableColumnIndex = false
}
// 鼠标移出事件
const onCellMouseLeave = (row, column, cell, event, index) => {
    styleColumn.value[row.index].tableColumnBtn = false
    styleColumn.value[row.index].tableColumnIndex = true
}

// 添加
function addItem() {
    let item = {
        "delImageIds": [],//	删除的工单费用图片对象ID
        "id": null,//配件物料ID，新增不必传，修改必传	
        "images": [],
        "model": "",//物料型号
        "name": "",//物料名称
        "overinsured": false,//物料质保状态：false-保内，true-保外
        "price": 0,//物料单价
        "qty": 1,//	物料数量,示例值(1)
        "remark": "",//备注
        "spareId": null,//	物料配件ID
        "specId": null,//物料配件规格ID
        "specName": "",//	物料配件规格名称
        "specSku": "",//商品规格编号
        "type": 1,//结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
        spareSelect: [],//配件
        spareSpecSelect: [],//规格
    }
    tableDataList.spareMaterialVos.push(item)
    sparePageSelectList('', tableDataList.spareMaterialVos.length - 1)
    styleColumn.value.push({
        tableColumnIndex: true,
        tableColumnBtn: false
    })
}
// 新增删除
function deleteItem(n: number) {
    if (tableDataList.spareMaterialVos.length == 1) {
        return
    }
    tableDataList.spareMaterialVos = tableDataList.spareMaterialVos.filter((o, index) => {
        return index != n
    })
    styleColumn.value.splice(n, 1)
}
watch(() => tableDataList.type, (n) => {
    if (n == 2) {
        tableDataList.networkSpareType = 1
    }
})
// 地址类型变化
const changeAddrType = (val: any) => {
    addrsDom.value.getSelectAddr()
    switch (val) {
        case 1:
            getWorkUserAddressData()
            break;
        case 2:
            getOrderNetworkAddressData()
            break;
        default:
            tableDataList.receiptName = ''
            tableDataList.receiptPhone = ''
            tableDataList.receiptAddress = ''
            tableDataList.receiptProvince = ''
            tableDataList.receiptCity = ''
            tableDataList.receiptArea = ''
            tableDataList.receiptTown = ''
            addrs.value = {
                province: '',
                city: '',
                area: '',
                town: ''
            }
            addrsDom.value.clearSelectAddr()
            break
    }
}
// 获取用户地址
const getWorkUserAddressData = () => {
    // getWorkUserAddress(workId.value).then(res => {
    //     if (res.data.success) {
    //         tableDataList.userOrNetworkId = res.data.data.row.id
    //         tableDataList.receiptName = res.data.data.row.name
    //         tableDataList.receiptPhone = res.data.data.row.phone
    //         tableDataList.receiptAddress = res.data.data.row.address
    //         tableDataList.receiptProvince = res.data.data.row.province
    //         tableDataList.receiptCity = res.data.data.row.city
    //         tableDataList.receiptArea = res.data.data.row.area
    //         tableDataList.receiptTown = res.data.data.row.town
    //         addrs.value = {
    //             province: tableDataList.receiptProvince,
    //             city: tableDataList.receiptCity,
    //             area: tableDataList.receiptArea,
    //             town: tableDataList.receiptTown
    //         }
    //     } else {
    //         ElMessage({
    //             showClose: true,
    //             message: res.data.message,
    //             duration: 4000,
    //             offset: 200,
    //             type: 'error'
    //         })
    //     }
    // })
}
// 获取服务商地址
const getOrderNetworkAddressData = () => {
    // getOrderNetworkAddress(workId.value).then(res => {
    //     if (res.data.success) {
    //         tableDataList.userOrNetworkId = res.data.data.row.id
    //         tableDataList.receiptName = res.data.data.row.name
    //         tableDataList.receiptPhone = res.data.data.row.phone
    //         tableDataList.receiptAddress = res.data.data.row.address
    //         tableDataList.receiptProvince = res.data.data.row.province
    //         tableDataList.receiptCity = res.data.data.row.city
    //         tableDataList.receiptArea = res.data.data.row.area
    //         tableDataList.receiptTown = res.data.data.row.town
    //         addrs.value = {
    //             province: tableDataList.receiptProvince,
    //             city: tableDataList.receiptCity,
    //             area: tableDataList.receiptArea,
    //             town: tableDataList.receiptTown
    //         }
    //     } else {
    //         ElMessage({
    //             showClose: true,
    //             message: res.data.message,
    //             duration: 4000,
    //             offset: 200,
    //             type: 'error'
    //         })
    //     }
    // })
}
// 获取配件下拉数据
const sparePageSelectList = async (val: string, index) => {
    let data = {
        limit: 0,
        name: val,
        page: 0
    }
    loading2.value = true
    await getOrderSparePageSelect(data, workId.value).then(res => {
        if (res.data.code == 20000) {
            tableDataList.spareMaterialVos[index].spareSelect = res.data.data.rows
            loading2.value = false
        } else {
            ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 3000
            })
        }
    })
}
// 配件变化
const changeSpareId = (id: any, index: string | number) => {
    tableDataList.spareMaterialVos[index].specId = null
    tableDataList.spareMaterialVos[index].specSku = ''
    tableDataList.spareMaterialVos[index].specName = ''
    tableDataList.spareMaterialVos[index].price = 0
    tableDataList.spareMaterialVos[index].spareSpecSelect = []
    if (id) {
        spareSpecPageSelectList('', id, index)
    }
}
// 规格变化
const clickSpecId = (id, index) => {
    if (!id) {
        tableDataList.spareMaterialVos[index].specSku = ''
        tableDataList.spareMaterialVos[index].specName = ''
        tableDataList.spareMaterialVos[index].price = 0
    }
}

// 获取规格下拉数据
const spareSpecPageSelectList = async (val: string, id: any, index) => {
    if (!id) {
        return
    }
    let data = {
        limit: 0,
        name: val,
        page: 0
    }
    loading2.value = true
    await getOrderSpareSpecSelect(data, id).then(res => {
        if (res.data.code == 20000) {
            tableDataList.spareMaterialVos[index].spareSpecSelect = res.data.data.rows
            loading2.value = false
        } else {
            ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 3000
            })
        }
    })
}
// 点击配件
const clickSpareId = (val, index: string | number) => {
    tableDataList.spareMaterialVos[index].model = val.model
    tableDataList.spareMaterialVos[index].name = val.name
}
// 点击配件规格
const clickspecId = (val: any, index: any) => {
    tableDataList.spareMaterialVos[index].specSku = val.specSkuCode
    tableDataList.spareMaterialVos[index].specName = val.name
    tableDataList.spareMaterialVos[index].price = tableDataList.spareMaterialVos[index].overinsured ? val.overPrice : val.price
}
// 质保状态改变
const onChangeOverinsured = (index) => {
    tableDataList.spareMaterialVos[index].spareSpecSelect.map(item => {
        if (tableDataList.spareMaterialVos[index].specId === item.id) {
            tableDataList.spareMaterialVos[index].price = tableDataList.spareMaterialVos[index].overinsured ? item.overPrice : item.price
            return
        }
    })
}
// 保存
async function onSaveBtn() {
    for (const key in tableDataList.spareMaterialVos) {
        let imgobj = tableDataList.spareMaterialVos[key];
        let arrimg = []
        if (imgobj.images.length > 0) {
            for (const i in imgobj.images) {
                arrimg.push(imgobj.images[i].file)
            }
            if (imgobj.images[0].file) {
                await orderAnnexUpload(arrimg).then(res => {
                    imgobj.images = res.data.data.rows.map(o => ({ id: null, image: o }))
                })
            }
        }
    }
    const addr = addrsDom.value.getSelectAddr()
    tableDataList.receiptProvince = addr.province
    tableDataList.receiptCity = addr.city
    tableDataList.receiptArea = addr.area
    tableDataList.receiptTown = addr.town
    if (tableDataList.type == 1) {
        tableDataList.networkSpareType = 1
    }
    tableDataList.workId = workId.value
    // await spareSaveOrder(tableDataList).then(res => {
    //     if (res.data.success) {
    //         ElMessage({
    //             showClose: true,
    //             message: res.data.message,
    //             type: 'success',
    //             offset: 200,
    //         })
    //         emits('update-list')
    //         onCancel()
    //     } else {
    //         ElMessage({
    //             showClose: true,
    //             message: res.data.message,
    //             duration: 4000,
    //             offset: 200,
    //             type: 'error'
    //         })
    //     }
    // })
}

// 删除图片
const handleRemove = (imgindex: number, index: string | number) => {
    tableDataList.spareMaterialVos[index].images = tableDataList.spareMaterialVos[index].images.filter((o, i) => i != imgindex)
}
// 查看图片
const handlePictureCardPreview = (img: any) => {
    dialogImageUrl.value = img
    dialogVisible.value = true
}
// 添加图片
const getProImages = async (img: any, index: any) => {
    if (tableDataList.spareMaterialVos[index].images.length >= 8) {
        ElMessage({
            showClose: true,
            message: '最多上传8个',
            duration: 4000,
            offset: 200,
            type: 'error'
        })
        return
    }
    tableDataList.spareMaterialVos[index].images.push({ image: img.url, file: img.raw })
}

const onCancel = () => {
    emits('assign-dialog')
}
onMounted(() => {
    nextTick(() => {
        setTimeout(() => {
            getWorkUserAddressData()
        }, 500)
        sparePageSelectList('', 0)
    })
})
</script>
<style lang="scss" scoped>
.title_top {
    border-left: 2px solid #007cff;
    line-height: 14px;
    padding-left: 6px;
    margin-bottom: 8px;
}

:deep(.el-form-item) {
    margin-right: 15px;
    margin-bottom: 14px;

    .el-cascader .el-input {
        width: 220px;
    }

    .item-input {
        width: 300px;
    }

    .item-input-phone {
        width: 180px;
    }

    .item-input_w {
        width: 390px;
    }

    .el-form-item__label {
        font-size: 12px;
    }
}

:deep(.el-form-item .el-cascader .el-input) {
    width: 390px;
}

.form_sction {
    display: flex;
    align-items: flex-start;
}

.operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
        cursor: pointer;
        margin: 0 6px;

        &:hover {
            transform: scale(1.2);
        }
    }
}

:deep(.el-table td.el-table__cell) {
    .el-input {
        .el-input__wrapper {
            height: 28px;
        }

        .el-input-group__prepend {
            padding: 0 2px;
        }
    }
}

.btn_save {
    width: 60px;
}

.btn_cancel {
    width: 60px;

    &:hover {
        border: 1px solid #e5e5e5;
        color: #999;
        background-color: #e5e5e5;
    }
}

.footer_remark {
    margin-top: 20px;

    .w_input {
        width:600px;
        margin-left: 10px;
    }
}

:deep(.updata_pic) {
    display: flex;
    align-items: center;

    .el-upload {
        &.el-upload--picture-card {
            width: 40px;
            height: 40px;
        }
    }

    .disf_ipc {
        display: flex;
        width: 40px;
        height: 40px;
        position: relative;
        margin-left: 6px;
        border: 1px solid #7f7f7f27;
        border-radius: 4px;
        box-sizing: border-box;
        overflow: hidden;

        .img {
            width: 100%;
            position: absolute;
            border-radius: 4px;
        }

        .item-actions {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0;
        }

        &:hover .item-actions {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #7f7f7f9d;
            opacity: 1;
            border-radius: 4px;

            .item-preview {
                margin: 0 4px;
                cursor: pointer;

                &:hover {
                    transform: scale(1.2);
                }
            }

            .item-delete {
                margin: 0 4px;
                cursor: pointer;

                &:hover {
                    transform: scale(1.2);
                }
            }
        }
    }
}</style>